package cn.itcast.security;

import cn.itcast.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UserDetaliService implements UserDetailsService {
    public static Map<String, User> map = new HashMap<>();

    static {
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword("012346");
        User user2 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword("012346");
        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);


    }

    /**
     * 根据用户名加载用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("usename=" + username);


        User user = map.get(username);//模拟根据用户名查询数据库
        if (user == null) {
            return null;

        }
        //模拟数据库中的密码，后期需要查询数据库
        String password = "{noop}" + user.getPassword();
//授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, password, list) {
        };
        return userDetails;
    }
}
